import React, { useState, useEffect,useRef } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,notification,Select,Divider,DatePicker,Modal,Tag} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'

import { Menu, Dropdown, Space} from 'antd';
import { DownOutlined ,ExclamationCircleOutlined} from '@ant-design/icons'

import {findTestPaper,editPaperStatuss,findTestPaperPublish,editTestInfoBatch,addTestPaper,pushPool} from 'api/index'
import classNames from "classnames";

import TaskAllocation from "components/Operations/task";
import PreviewSubject from 'components/LlxPreview/paper'
import ChangeStatus from "components/Operations/status";


const { RangePicker } = DatePicker;
const { confirm } = Modal;


// 新增弹框
const AddPaper = (props) =>{
const {isModalVisible, setIsModalVisible,dictionaries,userName} = props
const [form] = Form.useForm();//新增试卷
const loading = useRef(false)

  // 新增表单
const newWordItem = [
  {label: '试卷名称',type:'input', name: 'paperName' , span: 20 ,rules:[
    {
      required: true,
      message: '请输入试卷名称'
    },
  ]},
  {label: '级别', name: 'levelId', span: 20,rules:[
    {
      required: true,
      message: '请选择级别'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
  }},
  {label: '试卷类型', name: 'type', span: 20,rules:[
    {
      required: true,
      message: '请选择试卷类型'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择试卷类型'}
    options={[{id:'1',dictValue:'定级测试'},{id:'2',dictValue:'升级测试'}]}
  >
  </Select>
  }},
]

const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    form.validateFields().then(async()=>{

    

      const data = {
        paperName: form.getFieldValue().paperName,
        levelId: form.getFieldValue().levelId,
        type: form.getFieldValue().type,
        }
        
       await addTestPaper(data)

       notification.success({
          message: '新增成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
};

  const handleCancel = () => {
    form.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="新增试卷" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={form} labelCol={8} formItem={newWordItem} />
   </Modal>
} 
// 编辑弹框
const EditPaper = (props) =>{
const {isModalVisible, setIsModalVisible,dictionaries,userName,editForm} = props
const loading = useRef(false)

  // 表单
const newWordItem = [
  {label: '试卷名称',type:'input', name: 'paperName' , span: 20 ,rules:[
    {
      required: true,
      message: '请输入试卷名称'
    },
  ]},
  {label: '级别', name: 'levelId', span: 20,rules:[
    {
      required: true,
      message: '请选择级别'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
  }},
  {label: '试卷类型', name: 'type', span: 20,rules:[
    {
      required: true,
      message: '请选择试卷类型'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择试卷类型'}
    options={[{id:'1',dictValue:'定级测试'},{id:'2',dictValue:'升级测试'}]}
  >
  </Select>
  }},
]

const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    editForm.validateFields().then(async()=>{

      const data = {
        paperName: editForm.getFieldValue().paperName,
        levelId: editForm.getFieldValue().levelId,
        type: editForm.getFieldValue().type,
        id: editForm.getFieldValue().id,
        }
        
       await addTestPaper(data)

       notification.success({
          message: '编辑成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      
      editForm.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
};

  const handleCancel = () => {
    editForm.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="编辑试卷" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={editForm} labelCol={8} formItem={newWordItem} />
   </Modal>
} 


function PaperLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(true) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [id,setId] = useState('')
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisibleTask, setIsModalVisibleTask] = useState(false)
const [isModalVisibleStatus, setIsModalVisibleStatus] = useState(false)
const [isModalVisiblePreview, setIsModalVisiblePreview] = useState(false)
const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false)
const [selectData, setSelectData] = useState([])
const [form] = Form.useForm();//搜索列表
const [editForm] = Form.useForm();//

//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 表单数据
const formItem = !props.examineStatus?[
  {label: '名称',type:'input', name: 'paperName', span: 4 },
  {label: '试卷类型', name: 'type' , span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择试卷类型'}
    options={[{id:'1',dictValue:'定级测试'},{id:'2',dictValue:'升级测试'}]}
  >
  </Select>
}},
  {label: '状态', name: 'paperStatus', span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'dictValue',label:'dictValue'}}
    placeholder={'请选择状态'}
    options={dictionaries.wordStatus}
  >
  </Select>
}},
  {label: '级别', name: 'levelId' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
} },
  {label: '创建人', name: 'createBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择创建人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '负责人', name: 'manager',  span: 4 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择负责人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新人', name: 'updateBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择更新人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新时间', name: 'updateTime', span: 5 ,render: () => {
    return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}}
]:[
  {label: '名称',type:'input', name: 'paperName', span: 4 },
  {label: '试卷类型', name: 'type' , span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择试卷类型'}
    options={dictionaries.paperType}
  >
  </Select>
}},
  {label: '级别', name: 'levelId' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
} },
  {label: '创建人', name: 'createBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择创建人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新人', name: 'updateBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择更新人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新时间', name: 'updateTime', span: 5 ,render: () => {
    return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}}
]
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = !props.examineStatus?[
      {title: 'ID', dataIndex: 'paperCode', key: 'paperCode', align: 'center',width:100},
      {title: '试卷名称', dataIndex: 'paperName', key: 'paperName', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link" onClick={()=>goPaperInfo(record.id)}>
          {text}
       </div>
     }},
      {title: '分类', dataIndex: 'type', key: 'type', align: 'center',render: (text, record) => {
        return <div className="operate_link_group">
          {text===1?<Tag color="success">定级测试</Tag>:<Tag color="orange">升级测试</Tag>}
       </div>
     }},
      {title: '题数', dataIndex: 'subjectCount', key: 'subjectCount', align: 'center'},
      {title: '状态', dataIndex: 'paperStatus', key: 'paperStatus', align: 'center'},
      {title: '级别', dataIndex: 'levelName', key: 'levelName', align: 'center'},
      {title: '创建人', dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
     }},
      {title: '负责人', dataIndex: 'manager', key: 'manager', align: 'center', render: (text, record) => {
        return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {record.qmanager||record.rmanager}
       </div>
     }},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
     }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
      {title: '编辑', dataIndex: 'active', key: 'active', align: 'center',width:100,render:(text, record) => {
        return  <>
         <span className="text-link" onClick={()=>previewPaper(record)}>预览</span>&nbsp;&nbsp;&nbsp;
         <span className="text-link" onClick={()=>editPaper(record)}>编辑</span>
        </>
      }},
]:[
  {title: 'ID', dataIndex: 'paperCode', key: 'paperCode', align: 'center',width:100},
  {title: '试卷名称', dataIndex: 'paperName', key: 'paperName', align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goPaperInfo(record.id)}>
      {text}
   </div>
 }},
  {title: '分类', dataIndex: 'type', key: 'type', align: 'center',render: (text, record) => {
    return <div className="operate_link_group">
      {text===1?<Tag color="success">定级测试</Tag>: <Tag color="orange">升级测试</Tag>}
   </div>
 }},
 {title: '级别', dataIndex: 'levelName', key: 'levelName', align: 'center'},
  {title: '题数', dataIndex: 'subjectCount', key: 'subjectCount', align: 'center'},
  {title: '创建人', dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
    return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
 }},
  {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
    return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
  {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',width:100,render:(text,row)=>{
    return  <div className="text-link" onClick={()=>previewPaper(row)}>
     预览
   </div>
  }}
]





// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='test/testPaperLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='test/testPaperLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()

  
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{
  // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)

  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('test/testPaperLibrary',data) 

    const initialData = async () => {

      const {
        createBy,
        endTime,
        levelId,
        manager,
        paperName,
        startTime,
        updateBy,
        paperStatus,
        type
      } = form.getFieldValue()
      

      const params = {
        currPage:value&&value.pageSize?value.current:pagination.current,
        pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
        createBy,
        endTime,
        levelId,
        manager,
        paperName,
        startTime,
        updateBy,
        paperStatus,
        type
      }

       
      if(!props.examineStatus){
        const res = await findTestPaper(params)
        const data = res.result.records || []
        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
        })
        
        setDataSource(data)
  
        setTotal(res.result.total)
      } else {
        const res = await findTestPaperPublish(params)
        const data = res.result.records || []
        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
        })
        
        setDataSource(data)
  
        setTotal(res.result.total)
      }
    

      setLoading(false)
    
    }
  
    initialData()
    }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
//  3.预览试卷
const previewPaper = (value) =>{
  setId(value.id)
  setIsModalVisiblePreview(true)
}
//  4.试卷详情
const goPaperInfo = (id) => {
props.history.push('/view/test/testPaperInfo?id=' + id)
props.addRouter({
  menuName:'试卷详情',url:'test/testPaperInfo?id=' + id 
})
}
//  5.新增试卷
const addNewPaper = () => {
  setIsModalVisible(true)
}
//  6.更多操作
const moreOperation = (value) =>{
  // 判断是否选择了数据
  if(!selectedRowKeys.length){
    notification.warning({
      message: '请至少选择一项数据',
      duration:1.5
    });
    return
  }
  
  const data = dataSource.filter((i)=>selectedRowKeys.includes(i.id))

  setSelectData(dataSource.filter((i)=>selectedRowKeys.includes(i.id)))

  switch (value.key) {
    case 'taskOther':
    //  分配任务
    if(data.some(i=>i.wordStatus==='P')){
      notification.warning({
        message: '你的选择中含有已发布的数据，请重新选择',
        duration:1.5
      });
      return
    }
    setIsModalVisibleTask(true)
    break
    case 'statusCheck':
     //  修改状态
     setIsModalVisibleStatus(true)
    break
    case 'pushTestArea':
      //  添加到测试区
      confirm({
        title: '是否将选中的数据添加到测试区',
        icon: <ExclamationCircleOutlined />,
        onOk() {
         const http = async()=>{
          await pushPool({
            dataId: data.map(i => i.id),
            levelId: 255,
            poolId: 607,
            type: 'PAPER'
          })

          notification.success({
            message: '添加成功',
            duration:1.5
          });
         }

         http()
        },
        onCancel() {
          // 取消
        },
      });
     break
   default:
     return
  }
}
// 6.1.更多操作
const menu = (
 <Menu
    onClick={moreOperation}
    items={props.userInfo.user.userName==='郭玉颖'?[
      {
        label: '任务分配',
        key: 'taskOther',
      },
      {
        label: '状态退回',
        key: 'statusCheck',
      },
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      },
    ]:[
      {
        label: '添加至测试区',
        key: 'pushTestArea',
      },
    ]}
  />
);
// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}
// 8.编辑
const editPaper = (value) => {
  editForm.setFieldsValue({
    id:value.id,
    type:value.type + '',
    paperName:value.paperName,
    levelId:value.levelId
  })

  setIsModalVisibleEdit(true)
}
// 9.定级规则
// const addRule = () => {
//   message.error('待完善')
// }


return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>
    {/* 操作按钮 */}
    <div className="operate-btn">
     <div>
       {
          !props.examineStatus ? 
          <>
           <Button  onClick={addNewPaper} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>
           {/* <Button  onClick={addRule} type='primary' className='animate__animated animate__fadeInLeft'>定级规则配置</Button> */}
          </>:''
       }
       {
         !props.examineStatus ? <Dropdown overlay={menu}>
         <Button  className='animate__animated animate__fadeInLeft'>
           <Space>
            更多操作
           <DownOutlined />
          </Space>
        </Button>
       </Dropdown>:''
       }
       </div>
       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>
    </div>

    <Divider />
    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={true}
     rowSelection={rowSelection.current}
     height={!expand?320:380}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

     {/* 弹框 */}
     {/* 1.新增 */}
     <AddPaper dictionaries={dictionaries} getNewList={getNewList} userName={props.userInfo.user.userName}  isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></AddPaper>
     <EditPaper editForm={editForm} dictionaries={dictionaries} getNewList={getNewList} userName={props.userInfo.user.userName}  isModalVisible={isModalVisibleEdit} setIsModalVisible={setIsModalVisibleEdit}></EditPaper>
    {/* 任务分配 */}
     <TaskAllocation  editHttp={editTestInfoBatch} type={'PAPER'} statusType={'paperStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} UserSpecies={dictionaries.UserSpecies} list={selectData} isModalVisible={isModalVisibleTask} setIsModalVisible={setIsModalVisibleTask} ></TaskAllocation>
     {/* 状态变更 */}
     <ChangeStatus http={editPaperStatuss} type={'PAPER'} statusType={'paperStatus'}  userName={props.userInfo.user.userName} getNewList={getNewList} labelOption={dictionaries.Label} list={selectData} isModalVisible={isModalVisibleStatus} setIsModalVisible={setIsModalVisibleStatus} ></ChangeStatus>


    {/* 预览课后题 */}
    <PreviewSubject  id={id} isModalVisible={isModalVisiblePreview} setIsModalVisible={setIsModalVisiblePreview}></PreviewSubject>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {userBtnRole:state.userBtnRole,tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(PaperLibrary)
